package com.speedchina.permission.security.jwt;

import com.speedchina.framework.model.R;
import com.speedchina.framework.utils.ApplicationContextHolder;
import com.speedchina.framework.utils.JSONUtils;
import com.speedchina.permission.base.sysenum.SysErrorCodeEnum;
import com.speedchina.permission.properties.JwtProperties;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.springframework.util.StringUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * jwt 验证过滤器
 *
 * @author Winter
 * @create 2020-11-12 下午5:16
 **/

public class JwtAuthFilter extends BasicHttpAuthenticationFilter {

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setStatus(200);
        httpServletResponse.setContentType("application/json;charset=utf-8");

        PrintWriter out = httpServletResponse.getWriter();

        out.println(JSONUtils.toJSONString(R.error(SysErrorCodeEnum.SYS_TOKEN_UNVALID.getCode(),SysErrorCodeEnum.SYS_TOKEN_UNVALID.getMsg())));
        out.flush();
        out.close();
        return false;
    }
   @Override
   protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {
       return !StringUtils.isEmpty(getToken((HttpServletRequest)request));
   }

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {

        if (isLoginAttempt(request, response)) {
            try {
                executeLogin(request, response);
            } catch (Exception e) {
                return false;
            }
        }
        return true;
    }

    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
       String tokenString = getToken((HttpServletRequest)request);
        JWTToken token = new JWTToken(tokenString);
        getSubject(request, response).login(token);
        return true;
    }

    private String getToken(HttpServletRequest request) {
        JwtProperties jwtConfig = ApplicationContextHolder.getBean(JwtProperties.class);
        String token = request.getHeader(jwtConfig.getHeaderName());
        if(StringUtils.isEmpty(token)) {
            token = request.getParameter(jwtConfig.getHeaderName());
        }
        return token;
    }
    private void returnJson(ServletResponse response,Object message){
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(JSONUtils.toJSONString(message));
        } catch (IOException e){
        } finally {
            if(writer != null){
                writer.flush();
                writer.close();
            }
        }
        return;
    }
}
